#coding:utf-8
import sys
from PyQt5 import uic
from PyQt5.QtWidgets  import QApplication
from PyQt5.QtWidgets import QMainWindow

class Calc(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.x=None
        self.y=None
        self.result=None
        self.operator=None
        self.equal=None
        #self.clear=None
        uic.loadUi('calc.ui',self)
        btns=[
            self.pushButton0,
            self.pushButton1,
            self.pushButton2,
            self.pushButton3,
            self.pushButton4,
            self.pushButton5,
            self.pushButton6,
            self.pushButton7,
            self.pushButton8,
            self.pushButton9,
            self.pushButton_dot,
            self.pushButton_add,
            self.pushButton_sub,
            self.pushButton_mul,
            self.pushButton_div,     
            self.pushButton_equal,
            self.pushButton_clear
                ]
        map(lambda btn: btn.clicked.connect(self.click_on_button),btns)
    def calculate(self):
        '''
        如果x,y，operater不为空，计算结果
        '''
        if self.x and self.y and self.operator:
            s="%s%s%s"%(self.x,self.operator,self.y)
            print s
            self.result=str(eval(s))
            self.text_result.setText(self.result)





    def click_on_button(self):
        print '点击按钮前:',self.x,self.operator,self.y
        value =self.sender().text()
        #如果点击的是数字，print该运算符
        if value in '0123456789.':
            print '点击的数字是:',value
            try:
                if self.operator is None:
                #如果点击的是数字的话，保存到X或追加到X
                    if self.x is None:
                        self.x=value
                    else:
                        self.x +=value
                    self.text_result.setText(self.x)
                else:
                    if self.y is None:
                        self.y=value
                    else:
                        self.y +=value
                    self.text_result.setText(self.y)
            except Exception, e:
                print e
        elif  value in '+-*/':
            print '点击的运算符是:',value
            self.operator=value
            self.text_result.setText("")
        elif value == '=':
            print '点击的结果是=.'
            self.calculate()
            self.text_result.setText(self.result)
        else: 
            print '点击的C'
            self.clear()
        print '点击按钮后:',self.x,self.operator,self.y
    def clear(self):
        self.x=None
        self.y=None
        self.result=None
        self.operator=None
        self.text_result.setText("")
        
if __name__ == '__main__':    
    app = QApplication(sys.argv)
    calc = Calc()
    calc.show()
    app.exec_()




